//
//  ContentView.swift
//  JiaoZiTaxi
//
//  Created by Hu Gang on 2022/8/23.
//

import Combine
import ComposableArchitecture
import CoreLocation
import JZLocationConverterSwift
import Localize_Swift
import Logging
import MapKit
import SheeKit
import SwiftDate
import SwiftUI
import Localize_Swift
//计费方式
enum ModuleType {
    case charging
    case message
}

let counterReducer = AnyReducer<AppState, AppAction, AppEnvironment> {
    state, action, _ in
    switch action {
    case .callTaxi:
        state.orderState = .calling
        return .none
    case .waitingTaxi:
        state.orderState = .waiting
        return .none
    case .increment:
        state.passengerNum += 1
        return .none
    case .decrement:
        state.passengerNum -= 1
        if state.passengerNum < 1 {
            state.passengerNum = 1
        }
        return .none
    }
}
struct StaticButtonStyle: ButtonStyle {
    func makeBody(configuration: Configuration) -> some View {
        configuration.label
    }
}
struct ContentView: View {
    let logger = Logger(label: "view")
    let store: Store<AppState, AppAction>
    
    @ObservedObject var monitor = NetworkMonitor.shared
    @ObservedObject var service = WebSocketService.shared
    @ObservedObject var mapConfig = MapConfig.shared
    @ObservedObject var audioManager = AudioManager.shared
    @ObservedObject var carOrder = CarOrder.shared
    
    @Environment(\.scenePhase) var scenePhase
    
    @State var now: String = Date().toFormat("yyyy-MM-dd HH:mm:ss")
    var vm = ViewModel.shared
    
    @State var needMenu = false // 是否弹出菜单
    @State var needDebug = false // 是否弹出Debug
    @State var needChatWindow = false // 是否弹出聊天窗口
    @State var needLanguage = false // 是否弹出语言选择窗口
    @State var needInputPassengerInfo = false // 是否弹出个人信息输入框
    @State var needDistanceInfo = false // 是否弹出距离输入框
    @State var needAbout = false // About us
    @State var needLog = false // About us
    @State var needOrders = false // Order History
    @State var passengerInfo = PassengerInput()
    @State var needCallSpecTaxi = false // 特定叫车
    @State var showSelectCity = false // 是否显示城市选择
    @State var inited = false // 是否初始化
    
    @State var showingReceiveMessageAlert = false //是否接收消息
    @State var showingBillingMethodAlert = false //是否计费方式
    @State private var selectedDetentIdentifier: UISheetPresentationController.Detent.Identifier? = UISheetPresentationController.Detent.Identifier.medium
    
    let timer = Timer.publish(every: 20, on: .main, in: .common).autoconnect()
    var appName: String = AppHelper.shared.appName
    
    @State var showSelectMap: Bool = false
    @State var showSelectMapEnd: Bool = false
    @State var showCommonAddress: Bool = false
    @State private var region = MKCoordinateRegion(
        center: CLLocationCoordinate2D(latitude: ViewModel.shared.lastLocation.latitude, longitude: ViewModel.shared.lastLocation.longitude),
        span: MKCoordinateSpan(latitudeDelta: 0.005, longitudeDelta: 0.005)
    )
    @State private var showAlert = false
    
    
    @State private var isSettingActive: Bool = false //跳转设置页面
    
    @State private var isCommonActive: Bool = false //跳转常用地址页面
    
    @State private var cancellable: AnyCancellable?
    
    @State var distancePrice : PathCoordinate? // 打车的车费和距离
    
    
    @State var isConnected :Bool = true// 链接状态
 
    
    //版本更新
    @StateObject private var versionChecker = AppVersionChecker()
    @State private var showUpdateAlert = false
    @State private var showCancelAlert = false
    
    
    init(store: Store<AppState, AppAction>) {
        print("ContentView init....")
        self.store = store
        let info = vm.passenger
        passengerInfo.wechatNo = info.wechatNo
        passengerInfo.laosMobile = info.laosMobile
        
        logger.info("exist passenger:\(passengerInfo)")
        initOpenId()
        if let loc = LocationManager.shared.lastLocation {
            vm.lastLocation = loc.coordinate
        }
        
    }
    
    var body: some View {
        let drag = DragGesture()
            .onEnded {
                if $0.translation.width < -100 {
                    withAnimation {
                        self.needMenu = false
                        logger.info("close menu")
                    }
                }
            }
        
        WithViewStore(store) { viewStore in
            NavigationView {
                GeometryReader { geometry in
                    ZStack(alignment: .center) {
                        // MARK: -  地图
                        MapExView(config: mapConfig, service: service, showCallTaxiView: self.$needCallSpecTaxi)
                                    
                            .onTapGesture {
                                self.needMenu = false
                            }
                        
                        VStack {
                            // MARK: - 顶部状态视图
                            createTopStatusView().frame(height: 52)
//                                .background(Color.white)
//                                .cornerRadius(25)
                            Spacer()
                            // MARK: - 未打车视图
                            if service.orderState == .none && !self.needCallSpecTaxi {
                                createNoTakingTaxtView(viewStore: viewStore, geometry: geometry)
                            }
                        }
                        //全屏
                        .frame(maxWidth: .infinity, maxHeight: .infinity)
                        .ignoresSafeArea(edges: .bottom)
                        
                        // MARK: 计费方式 弹框
                        if self.showingBillingMethodAlert {
                            CustomAlertView(title:"计费方式".localized(), content: "我们是老挝政府正规出租车，车和司机都有营运手续，按照老挝政府出租车收费标准打表计价根据实际乘车距离计费。6:00-21:00是白班，21:00-6:00是晚班。白班起步距离是2公里，起步收费50000老币，超过2公里之后每公里10000老币，晚班起步距离是2公里，起步收费60000老币，超过2公里之后每公里12000老币。等待5分钟折算为1公里。".localized(), showingCustomAlert: $showingBillingMethodAlert)
                        }
                        
                        if self.showUpdateAlert {
                            CustomAlertView(title:"发现新版本".localized(), content: "\("有新版本".localized()) \(versionChecker.appInfo?.version ?? "") \("可用".localized())".localized(), showingCustomAlert: $showUpdateAlert) {
                               if let url = URL(string: versionChecker.appInfo?.trackViewUrl ?? "") {
                                  UIApplication.shared.open(url)
                                }
                            }
                        }
                        
                        // MARK: 温馨提醒 弹框
                        if self.showingReceiveMessageAlert {
                            CustomAlertView(title:"温馨提醒".localized(), content: "司机成功接单后超过5分钟，此时乘客撤销订单将需要支付违约费用(起步价)，提醒您做好出行计划后再叫车，避免撤销订单可能带来不必要的损失!".localized(), showingCustomAlert: $showingReceiveMessageAlert)
                        }
                        // MARK: 乘客信息
                        if self.needInputPassengerInfo {
                            VStack(spacing: 0) {
                                // 半透明背景
                                Color.black.opacity(0.4)
                                    .edgesIgnoringSafeArea(.all)
//                                Spacer()
                                UserInfoView(passenger: passengerInfo, showSheet: $needInputPassengerInfo)
                                
                            }
                            //全屏
                            .frame(maxWidth: .infinity, maxHeight: .infinity)
                            .ignoresSafeArea(edges: .bottom)
                        }
                        
                        
                        // MARK: - 正在等待车辆
                        if service.orderState == .waiting {
                            VStack (spacing: 0){
                                Spacer()
                                CarIsComingView(state: $service.orderState, showCancelAlert: $showCancelAlert,showChatWindow: $needChatWindow)
                            } //全屏
                            .frame(maxWidth: .infinity, maxHeight: .infinity)
                            .ignoresSafeArea(edges: .bottom)
                        }
                        
                        // MARK: - 开始行程，已上车
                        if service.orderState == .running {
                            VStack {
                                Spacer()
                                CarRuningView(showChatWindow: $needChatWindow)
                            }//全屏
                            .frame(maxWidth: .infinity, maxHeight: .infinity)
                            .ignoresSafeArea(edges: .bottom)
                        }
                        
                        // MARK: - 行程结束，待支付
                        
                        if service.orderState == .paying {
                            VStack {
                                Spacer()
                                OrderFinishView(showChatWindow: $needChatWindow)
                            }//全屏
                            .frame(maxWidth: .infinity, maxHeight: .infinity)
                            .ignoresSafeArea(edges: .bottom)
                        }
                        
                        // MARK: - 支付成功
                        if service.orderState == .payed && vm.isShowSuccessView {
                            VStack {
                                Spacer()
//                                OrderSuccessView(state: $service.orderState).padding()
                                OrderSuccessView(state: $service.orderState)
                            }
                            
                            .onDisappear {
                                
                                    // 视图消失时取消订阅
                                    cancellable?.cancel()
                                    cancellable = nil
                                vm.saveLastLocation()
                            }
                            .onAppear {
                              
                                // 在视图出现时订阅通知
                                cancellable =  NotificationCenter.default.publisher(for: .location)
                                    .receive(on: DispatchQueue.main)
                                    .sink {  _ in
                                        carOrder.startPos = ViewModel.shared.lastLocation
                                    }
                                
                                DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
                                    withAnimation {
                                        service.orderState = .none
                                        vm.isShowSuccessView = false
                                        // 上车位置清空
                                        carOrder.startPos =  ViewModel.shared.lastLocation
//                                        carOrder.startLabel = "\("出发地：\("自动定位")".localized())"
                                        // 下车地址清空
                                        carOrder.endPos = nil
                                        carOrder.endLabel = ""
                                        ViewModel.shared.endLocation = CLLocationCoordinate2DMake(0, 0)
                                        MapConfig.shared.startOrEndChanged = true
                                        // 清空订单号
                                    }
                                }
                            }
                        }
                        // MARK: 呼叫出租车距离
                        if self.needDistanceInfo {
                            VStack {
                                Spacer()
                                CallCarDistanceView( needDistanceInfo: self.$needDistanceInfo)
                                { fanwei in
                                    
                                    let loc = CarOrder.shared.passengerPosition!
                    
                    
                                    var lat = UserDefaults.standard.double(forKey: "lastLocation.lat")
                                    var lon = UserDefaults.standard.double(forKey: "lastLocation.lon")
                    
                                    let passenger = PassengerInput().read()!
                    
                    
                                    if let pos = CarOrder.shared.startPos {
                                        lat = pos.latitude.rounded(6)
                                        lon = pos.longitude.rounded(6)
                                    }
                    
                                    var lat2 = 0.0
                                    var lon2 = 0.0
                    
                                    if let pos = CarOrder.shared.endPos {
                                        lat2 = pos.latitude.rounded(6)
                                        lon2 = pos.longitude.rounded(6)
                                    }
                    
                                    let calldata = DataCall(lon: lon, lat: lat,lon2: lon2, lat2: lat2, phone: passenger.laosMobile, wechat: passenger.wechatNo, peopleNum: viewStore.passengerNum,fanwei: fanwei)
                    
                                    logger.info("call data:\(calldata)")
                    
                                    Api.callCars(callInfo: calldata) { r in
                                        switch r {
                                        case .failure(let error):
                                            logger.info("call cars error:\(error)")
                    
                                        case .success(let data):
                                            logger.info("call cars: \(data)")
                    
                                            DispatchQueue.main.sync {
                                                vm.nearCarCount = data.driverCounts
                                                logger.info("叫车返回车辆数量：\(data.driverCounts)")
                                            }
                    
                                            if let _ = data.workerID, let _ = data.name {
                                                let carOrder = vm.order
                                                carOrder.orderId = "\(data.id!)"
                                                carOrder.driverId = data.openid!
                                                carOrder.passengerId = calldata.openid
                                                carOrder.driverPhone = "\(data.laosPhone!)"
                                                carOrder.driverWechat = "\(data.phone ?? "")"
                                                carOrder.carNo = data.chepai!
                                                carOrder.save()
                                                var linghuo = calldata
                                                linghuo.hujiao = 1
                                                linghuo.id = "\(data.id!)"
                                                linghuo.receiverJSON = ""
                                                var callInfos: [DataCall] = []
                                                callInfos.append(linghuo)
                                                service.callCar(callInfo: callInfos, orderId: carOrder.orderId, driverId: carOrder.driverId){
                                                   
                                                    DispatchQueue.main.async {
                                                        service.orderState = .calling
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            //全屏
                            .frame(maxWidth: .infinity, maxHeight: .infinity)
                            .ignoresSafeArea(edges: .bottom)
                        }
                        // MARK: 呼叫出租车
                        if service.orderState == .calling {
                            VStack {
                                Spacer()
                                CallCarView(service: self.service, state: $service.orderState)
                            }
                            //全屏
                            .frame(maxWidth: .infinity, maxHeight: .infinity)
                            .ignoresSafeArea(edges: .bottom)
                        }
                        VStack {
                            if self.needMenu {
                                
                                SideMenuView(showSelf: self.$needMenu, showSheet: self.$needInputPassengerInfo, showDebug: self.$needDebug, showLog: self.$needLog, showAbout: self.$needAbout, showOrders: self.$needOrders)
                                    .frame(width: geometry.size.width * 2 / 3)
                                    .offset(x: 0 - geometry.size.width / 4)
                            }
                            
                            if self.needDebug {
                                DebugView(showDebug: self.$needDebug).frame(width: geometry.size.width - 30)
                            }
                            
                            if monitor.status != .connected || !isConnected  {
                                NetworkNotReadyView()
                            }
                            
                            // 指定Taxi
                            if self.needCallSpecTaxi {
                                //_ = logger.info("call spec car window showing...")
                                Spacer()
                                CallSpecCarView(showCallWindow: self.$needCallSpecTaxi, parent: self)
                                    .frame(width: geometry.size.width)
                            }
                            
                            // 语言选择
                            if self.needLanguage {
                                HStack {
                                    Spacer()
                                    LanguageView(showMe: self.$needLanguage)
                                        .frame(width: 220, height: 160)
                                        .shadow(color: Color.black.opacity(0.3), radius: 20, x: 0, y: 10)
                                        .padding(.top, 80)
                                        .padding(.trailing, 10)
                                }
                                Spacer()
                            }
                            
                            // 选择城市
                            if showSelectCity {
                                Spacer()
                                VStack {
                                    Text("选择您所在的城市")
                                        .font(.title3)
                                        .padding(.top,8)
                                    
                                    List {
                                        ForEach(vm.getCities()) { city in
                                            Text(city.name)
                                                .onTapGesture {
                                                    vm.currentCity = city.code
                                                    vm.currentCityName = vm.getCurrentCityName()
                                                    self.showSelectCity = false
                                                }
                                        }
                                    }
                                }
                                .background(content: {
                                    RoundedRectangle(cornerRadius: 8)
                                        .fill(Color.white)
                                })
                                .frame(width: geometry.size.width - 40, height: 360)
                                .shadow(color: Color.black.opacity(0.3), radius: 20, x: 0, y: 10)
                                .padding(.bottom, 20)
                            }
                        }
                        .onTapGesture {
                            self.needMenu = false
                        }
                        
                        if LocationManager.shared.statusString == "unknown" || LocationManager.shared.statusString == "notDeterminded" || LocationManager.shared.statusString ==
                            "denied"
                        {
                            Button("叫车服务需要打开地理位置权限") {
                                if let url = URL(string: "app-settings://LOCATION_SERVICES/com.jiaozichuxing.taxiapp") {
                                    UIApplication.shared.open(url)
                                }
                            }
                            .foregroundColor(.white)
                            .font(.system(size: 20))
                            .padding(20)
                            .background(
                                RoundedRectangle(cornerRadius: 10.0)
                                    .fill(Color(hex: "FF862F8D")))
                        }
                    }
                    
                    
                    .navigationBarTitle("轿子出行", displayMode: .inline)
                    .navigationBarHidden(true)
                    .navigationBarItems(leading:
                                            Button(action: {
                        withAnimation {
                            self.needMenu = true
                        }
                        logger.info("Profile button pressed...")
                    }) {
                        Image(systemName: "person.crop.circle").imageScale(.large).foregroundColor(Color(hex: "FF862F8D"))
                    },
                                        trailing:
                                            HStack {
                        if !vm.cities.isEmpty {
                            Button {
                                print("change city")
                                self.showSelectCity = true
                            } label: {
                                HStack {
                                    Image(systemName:"building.2")
                                        .font(.footnote)
                                    Text("\(vm.currentCityName)")
                                        .font(.subheadline)
                                    
                                }.foregroundColor(.white)
                                    .padding(.horizontal, 6)
                                    .padding(.vertical, 3)
                                    .background {
                                        RoundedRectangle(cornerRadius: 8)
                                            .fill(Color("mainColor"))
                                    }
                            }.padding(.trailing,2)
                            
                            
                            Button(action: {
                                logger.info("Language button pressed...")
                                self.needLanguage.toggle()
                            }) {
                                if vm.language == .Chinese {
                                    Text("中文").foregroundColor(Color(hex: "FF862F8D"))
                                        .font(.subheadline)
                                } else if vm.language == .English {
                                    Text("English").foregroundColor(Color(hex: "FF862F8D"))
                                        .font(.subheadline)
                                } else if vm.language == .Laos {
                                    Text("ພາສາລາວ").foregroundColor(Color(hex: "FF862F8D"))
                                        .font(.subheadline)
                                }
                            } // end button
                        } // end if
                    } // end HStack
                    ) // end nav bar items
                }
            }
            .gesture(drag)
            //版本更新
            .onReceive(versionChecker.$updateAvailable) { available in
                print("Update available: \(available)")
                if available {
                    DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
                        // 这里是延迟1秒后要执行的代码
                        print("延迟1秒后执行")
                        showUpdateAlert = true
                    }
                }
            }
//            .alert(isPresented: $showUpdateAlert) {
//               Alert(
//                title: Text("发现新版本".localized()),
//                   message: Text("\("有新版本".localized()) \(versionChecker.appInfo?.version ?? "") \("可用".localized())"),
//                primaryButton: .default(Text("更新".localized())) {
//                       if let url = URL(string: versionChecker.appInfo?.trackViewUrl ?? "") {
//                           UIApplication.shared.open(url)
//                       }
//                   },
//                   secondaryButton: .cancel(Text("取消".localized()))
//               )
//           }
            .alert(isPresented: $showCancelAlert) {
               Alert(
                title: Text("重要提醒".localized()),
                message: Text("此订单将被取消"),
                primaryButton: .default(Text("确定".localized())) {
                    WebSocketService.shared.orderState = .canceling
                },
                secondaryButton: .cancel(Text("取消".localized())){
                })
           }
            .onAppear {
                WebSocketService.shared.initWebSocketManager()
                versionChecker.checkForUpdates()
                logger.info("view appearing ...")
             
                // 请求通知权限
                UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) { granted, _ in
                    // 检查权限是否被授予
                    if granted {
                        logger.info("通知权限已授予")
                    } else {
                        logger.info("通知权限未授予")
                    }
                }
                // 读取设置
                let settings = UserDefaults.standard
                
                // 读取具体设置项
                let debugMode = settings.bool(forKey: "debugModeEnabled_preference")
                
                if debugMode {
                    WebSocketService.shared.baseUrl = URL(string: "wss://test.zhuiso.cn/wss/jcy/websocket/chat")
                    Constants.apiBaseUrl = "https://test.zhuiso.cn"
                    logger.info("当前处于调试模式")
                }
                
                logger.info("GPS:\(LocationManager.shared.statusString)")
                
                JZLocationConverter.start { error in
                    if error != nil {
                        logger.info("火星坐标修正服务启动失败")
                    } else {
                        logger.info("火星坐标修正服务启动成功")
                    }
                }
                
                if monitor.status == .connected {
                    initLoad()
                    self.inited = true
                }
                
                NotificationCenter.default.addObserver(forName: UIApplication.willTerminateNotification, object: nil, queue: .main) { _ in
                    logger.info("App willTerminateNotification")
                    CarOrder.shared.save()
                }
                
                let currentLanguage = Localize.currentLanguage()
                print("Current language 2:  \(currentLanguage)")
                print("当前位置".localized())
                
            }
//            .onChange(of: LocationManager.shared.locationStatus, perform: { newValue in
//                logger.info("GPS:\(String(describing: newValue))")
////                if carOrder.startLabel == NSLocalizedString("当前位置",comment:"当前位置") {
//                    carOrder.startPos = ViewModel.shared.lastLocation
////                }
//            })
            
            .onChange(of: monitor.status, perform: { status in
                if status == .connected, !inited {
                    initLoad()
                    self.inited = true
                }
            })
            .onChange(of: service.orderState, perform: { newValue in
                logger.info("state on change:\(newValue)")
                if newValue == .canceling {
                    self.distancePrice = nil
                    let carOrder = vm.order
                    service.cancelOrder(orderId: carOrder.orderId)
                    self.service.orderState = .none
                    CarOrder.shared.clear()
                    MapConfig.shared.annotationItems.removeAll()
                    MapConfig.shared.route = nil
                    MapConfig.shared.followMode = false
                    MapConfig.shared.changed = true
                }
                
                if newValue == .none {
                    self.distancePrice = nil
                    MapConfig.shared.route = nil
                    MapConfig.shared.changed = true
                    CarOrder.shared.clear()
                    MapConfig.shared.annotationItems.removeAll()
                    MapConfig.shared.route = nil
                    MapConfig.shared.followMode = false
                    MapConfig.shared.changed = true
                    Task.detached(operation: {
                        await listCarsAsync() // 重新加载所有运营车辆信息
                    })
                }
            })
            .onChange(of: scenePhase) { newPhase in
                if newPhase == .active {    // 程序激活了
                    logger.info("Active")
                    service.appInBackground = false
                    self.service.connect()
                    if service.orderState == .calling {
                        service.orderState = .canceling
                    }
                    // 离线消息
                    if service.orderState == .waiting || service.orderState == .running || service.orderState == .paying || service.orderState == .pausing {
                        listUnreadMessages()
                    }
                    loadLastOrder()
                } else if newPhase == .inactive {      // 程序挂起
                    logger.info("Inactive")
                    service.appInBackground = false
                } else if newPhase == .background {    // 程序进入后台
                    logger.info("Background")
                    self.vm.saveLastLocation()
                    service.appInBackground = true
                }
            }
            .onReceive(NotificationCenter.default.publisher(for: .location), perform: { info in
//                if let userInfo = info.userInfo, let coordinate = userInfo["location"] as? CLLocationCoordinate2D {
//                    // 处理位置数据
//                    
//                    Api.googleNearbyPlaces(openId: vm.passenger.openId, latitude:"\(coordinate.latitude)" , longitude: "\(coordinate.longitude)") { r in
//                        switch r {
//                        case .success(let addresses):
//                            print("查询到的地址\(addresses)")
//                            DispatchQueue.main.async {
//                                if addresses.first != nil {
//                                    let address =  addresses.first!
//                                    print("通过地图拿到开始的的位置 \(address.longname ?? "无")")
//                                    var longitude = address.longitude!
//                                    var latitude = address.latitude!
//                                    var pos = CLLocationCoordinate2DMake(latitude, longitude)
//                                    
//                                 
//                                    // 更安全的写法，处理startPos为nil的情况
//                                    if let startPos = carOrder.startPos {
//                                        self.carOrder.startLabel = "\(address.longname ?? "无") \(startPos.distance(to: pos))"
//                                    } else {
//                                        self.carOrder.startLabel = "\(address.longname ?? "无") "
//                                    }
//                                    
//                                    
//                                }
//
//                            }
//                        case .failure(let addresses):
//                            print("\(addresses)")
//                        }
//                    }
//                }

               
            })
            .onReceive(NotificationCenter.default.publisher(for: .distancePrice), perform: { info in
                let object = info.userInfo!["distancePrice"] as! PathCoordinate
                self.distancePrice = object
                
            })
            .onReceive(NotificationCenter.default.publisher(for: .newMessage), perform: { _ in
                print("[ContentView][socket message] on Receive published new message.")
                audioManager.playNewMessage()
            })
            .onReceive(NotificationCenter.default.publisher(for: .callSpecCar), perform: { info in
                let carNo = info.userInfo!["car"] as! String
                let selectCar = vm.cars!.first { car in
                    car.carNo == carNo
                }
                logger.info("recieved call spec car.\(String(describing: selectCar))")
                self.vm.car = selectCar
                self.needCallSpecTaxi.toggle()
                
            })
            .onReceive(NotificationCenter.default.publisher(for: UIApplication.didBecomeActiveNotification)) { _ in
                print("App became active")
            }
            .onReceive(timer) { _ in
                // self.now  = Date().toFormat("yyyy-MM-dd HH:mm:ss")
                if vm.passenger.openId.isEmpty {
                    initOpenId()
                }
//                self.service.live()
                if self.service.orderState == .none {
                    Task.detached(operation: {
                        await listCarsAsync()
                    })
                }
            }
            .sheet(isPresented: $needChatWindow, onDismiss: {
                logger.info("chat window close.")
            }, content: {
                ChatView(chat: .hello)
            })
            .sheet(isPresented: $needAbout) {
                AboutUsView()
            }
            .sheet(isPresented: $needOrders) {
                OrdersView()
            }
            .task {
                listCities()
                listShortMessages()
            }
            // nav view
        }
        
    }
    

    // 切换语言
    func swichLanguage() {
//        carOrder.startLabel = "\("出发地：\("自动定位")".localized())"
    }
    
    func didDismiss() {}
    
    func initOpenId() {
        if vm.passenger.openId.isEmpty {
            Api.login(account: PhoneDevice().deviceId!.uuidString, password: "123456") { r in
                switch r {
                case .success(let data):
                    logger.info("login result:\(data)")
                    print("openId:\(data)")
                    DispatchQueue.main.sync {
                        vm.passenger.openId = data
                        Singleton.shared.openId = data
                        reportToken()
                    }
                    
                case .failure(let err):
                    logger.info("login error:\(err.localizedDescription)")
                }
            }
        } else {
            reportToken()
        }
    }
    
    func initLoad() {
        if vm.passenger.openId.isEmpty {
            initOpenId()
        }
        
//        service.connect()
        loadLastOrder()
        Task.detached(operation: {
            await listCarsAsync()
        })
    }
    
    func listUnreadMessages() {
        logger.info("listUnreadMessages: ====>")
        Api.listUnreadMessagesV2(openId: vm.passenger.openId, detectionId: vm.order.orderId) { r in
            print("api response:\(r)")
            
            switch r {
            case .failure(let err):
                logger.error("listUnreadMessages:\(err.localizedDescription)")
            case .success(let rr):
                logger.info("response:\(rr.count) messages")
                DispatchQueue.main.async {
                    UIApplication.shared.applicationIconBadgeNumber = 0
                }
                if rr.count > 0 {
                    print("收到新消息：\(rr.count)")
                    for source in rr {
                        print(source.message)
                        let str = source.message
                        MessageHelper.shared.parse(num: rr.count, content: str)
                    }
                }
            }
        }
    }
    
    // 列出所有的在运行车辆（Async）
    func listCarsAsync() async {
        do {
            let cars: [NewCarModel] = try await Api.listAllCarsAsync()
            logger.info("listCars result:\(cars)")
            DispatchQueue.main.async {
                mapConfig.annotationItems = []
                vm.cars = nil
                vm.cars = [CarInfo]()
                cars.forEach { car in
                    let location = CLLocationCoordinate2D(latitude: Double(car.lat)!, longitude: Double(car.lon)!)
                     let carNo = car.chepai ?? ""
                        
//                    let carNo = car.chepai.count <= 0 ?"":car.chepai
                    let driverMobile = car.driverLaosPhone.count <= 0 ? "":car.driverLaosPhone
                    var carStatus = EnumCarStatus.idle
                    if car.status != 1 {
                        carStatus = EnumCarStatus.busy
                    }
                    var owner = String(car.id)
                    let carInfo = CarInfo(id: owner, carNo: carNo, driverMobile: driverMobile, direction: 0, speed: 0, status: carStatus)
                    vm.cars?.append(carInfo)
                    mapConfig.annotationItems.append(MapAnnotationModel(coordinate: location, car: carInfo))
                }
            }
        } catch {
            logger.error("listCarsAsync error:\(error)")
        }
    }
    // 列出所有的在运行车辆
    func listCars() {
        Api.listAllCars { r in
            switch r {
            case .failure(let err):
                logger.info("listCars error:\(err.localizedDescription)")
                
            case .success(let cars):
                logger.info("listCars result:\(cars)")
                DispatchQueue.main.async {
                    mapConfig.annotationItems = []
                    vm.cars = nil
                    vm.cars = [CarInfo]()
                    vm.nearCarCount = cars.count
                    logger.info("周围车辆数量：\(cars.count)")
                    cars.forEach { car in
                        logger.info("\(car)")
                        let location = CLLocationCoordinate2D(latitude: Double(car.lat)!, longitude: Double(car.lon)!)
//                        let carNo = car.chepai
                        let carNo = car.chepai ?? ""
                        let driverMobile = car.driverLaosPhone
                        var carStatus = EnumCarStatus.idle
                        if car.status != 1 {
                            carStatus = EnumCarStatus.busy
                        }
                        let carInfo = CarInfo(id: String(car.id), carNo: carNo, driverMobile: driverMobile, direction: 0, speed: 0, status: carStatus)
                        vm.cars?.append(carInfo)
                        mapConfig.annotationItems.append(MapAnnotationModel(coordinate: location, car: carInfo))
                    }
                }
            }
        }
    }
    
    func callSpecCar(driverId: String) {
        let logger = Logger(label: "api-callSpecCar")
        let passengerNum = 1
        if passengerInfo.laosMobile.count == 0 || passengerInfo.wechatNo.count == 0 {
            needInputPassengerInfo = true
            return
        }
        service.orderState = .calling
        let loc = CarOrder.shared.passengerPosition!
        
        JZLocationConverter.default.wgs84ToGcj02(loc) { location in
            let passenger = PassengerInput().read()!
            
            var lat = loc.latitude.rounded(6)
            var lon = loc.longitude.rounded(6)
            
            if let pos = CarOrder.shared.startPos {
                lat = pos.latitude.rounded(6)
                lon = pos.longitude.rounded(6)
            }
            
            var lat2 = 0.0
            var lon2 = 0.0
            
            if let pos = CarOrder.shared.endPos {
                lat2 = pos.latitude.rounded(6)
                lon2 = pos.longitude.rounded(6)
            }
            
            let calldata = DataCall(lon: lon, lat: lat,lon2: lon2, lat2: lat2, phone: passenger.laosMobile, wechat: passenger.wechatNo, peopleNum: passengerNum,fanwei: CarOrder.shared.fanwei)
            
            logger.info("call data:\(calldata)")
            
            Api.callSpecCar(ownderId: driverId, callInfo: calldata) { r in
                switch r {
                case .failure(let error):
                    logger.info("error:\(error)")
                    
                case .success(let data):
                    logger.info("response:\n\(data)")
                    let carOrder = vm.order
                    carOrder.orderId = "\(data.id)"
                    carOrder.driverId = driverId
                    carOrder.passengerId = calldata.openid
                    carOrder.driverPhone = "\(data.laosPhone!)" 
                    carOrder.driverWechat =  "\(data.phone!)"
                    carOrder.carNo = data.chepai!
                    carOrder.save()
                    var linghuo = calldata
                    linghuo.hujiao = 1
                    linghuo.id = "\(data.id)"
                    linghuo.receiverJSON = ""
                    var callInfos: [DataCall] = []
                    callInfos.append(linghuo)
                    
                    service.callCar(callInfo: callInfos, orderId: carOrder.orderId, driverId: carOrder.driverId){
                        
                    }
                }
            }
        }
    }
    
    func loadLastOrder() {
        if let lastOrderId = UserDefaults.standard.string(forKey: "OrderId") {
            if lastOrderId.count > 0 {
                let openId = ViewModel.shared.passenger.openId
                Api.loadOrder(openId: openId, orderId: lastOrderId) { r in
//                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                        switch r {
                        case .failure(let err):
                            logger.info("load last order error:\(err)")
                        case .success(let rr):
                            logger.info("current order status:\(rr)")
                            MapConfig.shared.startOrEndChanged = true
                            DispatchQueue.main.sync {
                                switch rr {
                                case "1":
                                    self.service.orderState = .waiting
                                case "2":
                                    self.service.orderState = .running
                                case "3":
                                    self.service.orderState = .paying
                                    
                                    if !DataManager.shared.checkOrderExist(orderNo: lastOrderId) {
                                        // 获取订单总结
                                        Api.loadOrderSummary(openId: openId, detectionId: lastOrderId) { r in
                                            switch r {
                                            case .failure(let err2):
                                                logger.info("load order summary failure:\(err2)")
                                            case .success(let rr2):
                                                let newOrder = TaxiOrder(context: DataManager.shared.persistentContainer.viewContext)
                                                newOrder.endTime = Date().toStandardString
                                                newOrder.startTime = Date(timeIntervalSince1970: TimeInterval(CarOrder.shared.startTime)).toStandardString
                                                newOrder.distance = NSDecimalNumber(string: rr2.mydistance)
                                                newOrder.carNo = rr2.chepai
                                                newOrder.price = NSDecimalNumber(string: rr2.price)
                                                newOrder.orderNo = lastOrderId
                                                DataManager.shared.addOrder(order: newOrder)
                                            }
                                        }
                                    }
                                    
                                case "4":
                                    self.service.orderState = .none
                                    CarOrder.shared.clear()
                                default:
                                    logger.info("error code:\(rr)")
                                }
                                
                            }

                        }
                        
                        if service.orderState == .waiting || service.orderState == .running || service.orderState == .paying || service.orderState == .pausing {
                            listUnreadMessages()
                        }
//                    }
                }
            } else {
                CarOrder.shared.clear()
                carOrder.startPos = ViewModel.shared.lastLocation
//                carOrder.startLabel = "\("出发地：\("自动定位")".localized())"
                MapConfig.shared.startOrEndChanged = true
            }
        }
    }
    
    func reportToken() {
        let token = vm.deviceToken
        let openId = vm.passenger.openId
        logger.info("updateToken:\(openId) \(token)")
        if token.count > 0 && openId.count > 0 {
            Api.updateToken(openId: openId, token: token) { r in
                switch r {
                case .failure(let error):
                    logger.info("updateToken error:\(error)")
                    
                case .success(let data):
                    logger.info("updateToken success:\n\(data)")
                }
            }
        }
    }
    
    func listShortMessages() {
        Api.getAllShortMessages { r in
            print("api getAllShortMessages response:\(r)")
            
            switch r {
            case .failure(let err):
                logger.error("getAllShortMessages:\(err.localizedDescription)")
            case .success(let rr):
                logger.info("response:\(rr.count) messages")
                
                DispatchQueue.main.async {
                    vm.shortMessages = rr
                }
            }
        }
    }
    
    func listCities() {
        Api.getAllCities { r in
            print("api getAllCities response \(r)")
            switch r {
            case .failure(let err):
                logger.error("getAllCities error:\(err.localizedDescription)")
            case .success(let rr):
                DispatchQueue.main.async {
                    vm.cities = rr
                    vm.initCurrentCity()
                }
            }
        }
    }
    func makeRichText(baseText:String)->AttributedString{
    
        let plainString = "\("从".localized())「\(baseText)」\("出发".localized()) >"
        var attributedString = AttributedString(plainString)
        attributedString.foregroundColor = .black
        attributedString.backgroundColor = .white
        //[Range<String.Index>]
        // 设置部分文本的字体和颜色
        if let range = attributedString.range(of: baseText) {
           attributedString[range].font = .system(size: 14, weight: .bold)
            attributedString[range].foregroundColor = Color.themeColor()
        }
        
        return attributedString
    }
}


private extension ContentView {
    
    func distancePriceFix(distance : Double )-> String {
        let formatted = String(format: "%.2f", distance)
          return formatted
    }
    
    func createNoTakingTaxtView(viewStore : ViewStore<AppState,AppAction>  , geometry: GeometryProxy) -> some View {
            VStack{
//            //计费方式
//            ModuleView(image: "首页_计费方式", title: "计费方式".localized(), action: {
//                self.showingBillingMethodAlert = true
//            }, rImage: "首页_定位", subAction: {
//                NotificationCenter.default.post(name: .gotoCurrentLocation, object: nil)
//            }, type: ModuleType.charging, showingCustomAlert: $showingBillingMethodAlert)
    
                HStack{
                    Spacer()
                    Button {
                        
                            if LocationManager.shared.statusString == "unknown" || LocationManager.shared.statusString == "notDeterminded" || LocationManager.shared.statusString ==
                                "denied"
                            {
                                if let url = URL(string: "app-settings://LOCATION_SERVICES/com.jiaozichuxing.taxiapp") {
                                    UIApplication.shared.open(url)
                                }
                                return
                            }
                            
                            
                            
                        NotificationCenter.default.post(name: .gotoCurrentLocation, object: nil)
                    } label: {
                        Image("首页_定位")
                            .resizable()
                            .frame(width: 40, height: 40)
                }
                
                }.padding(.horizontal,15)
            //接收消息
            ModuleView(image: "首页_计费方式", title: "计费方式".localized(), action: {
//                self.needChatWindow = true
                self.showingBillingMethodAlert = true
            }, rImage: "首页_订阅", subAction: {
                self.showingReceiveMessageAlert = true
            }, type: ModuleType.charging, showingCustomAlert: $showingReceiveMessageAlert).padding(.horizontal,15)
    
                if let model = self.distancePrice {
                    MoneyDistanceView(model:model).padding(.horizontal,15)
                }
                
                
                
                
            VStack(alignment: .leading,spacing: 10) {
                    Text("出租车").background {
                        Image("首页_出租车背景").resizable()
                    }.font(.system(size: 18,weight: .bold))
                HStack(){
    
                    Text(makeRichText(baseText:  " \($carOrder.startLabel.wrappedValue)"))
                        .frame(height: 30)
                        .font(.system(size: 12))
                    Spacer()
                }
                .onTapGesture(perform: {
                    print("start label tapped")
                    //                                            self.showSelectMap = true
                    //                                            if let pos = carOrder.startPos {
                    //                                                if pos.longitude == 0 || pos.latitude == 0 {
                    //                                                    carOrder.startPos = ViewModel.shared.lastLocation
                    //                                                    region = MKCoordinateRegion(
                    //                                                        center: ViewModel.shared.lastLocation,
                    //                                                        span: MKCoordinateSpan(latitudeDelta: 0.005, longitudeDelta: 0.005)
                    //                                                    )
                    //                                                } else {
                    //                                                    region = MKCoordinateRegion(
                    //                                                        center: CLLocationCoordinate2D(latitude: pos.latitude, longitude: pos.longitude),
                    //                                                        span: MKCoordinateSpan(latitudeDelta: 0.005, longitudeDelta: 0.005)
                    //                                                    )
                    //                                                }
                    //
                    //                                            } else {
                    //                                                region = MKCoordinateRegion(
                    //                                                    center: CLLocationCoordinate2D(latitude: ViewModel.shared.lastLocation.latitude, longitude: ViewModel.shared.lastLocation.longitude),
                    //                                                    span: MKCoordinateSpan(latitudeDelta: 0.005, longitudeDelta: 0.005)
                    //                                                )
                    //                                            }
                }) .fullScreenCover(isPresented: self.$showSelectMap) {
                    // MARK: 出发地点--定位页面
                    ZStack {
                        if let pos = carOrder.startPos {
                            AddressManager(region: self.region, selectCoordinate: pos, selectType: "start") {
                                
                            }
                        } else {
                            AddressManager(region: self.region, selectCoordinate: vm.lastLocation, selectType: "start"){
                                
                            }
                        }
    
                    }
                }
    
                .onAppear() {
                    print("页面出现了")
                    if let pos = carOrder.startPos {
    
                    }else{
                        carOrder.startPos = ViewModel.shared.lastLocation
                    }
    
                    var coordinate = carOrder.startPos!;
                    Api.googleNearbyPlaces(openId: vm.passenger.openId, latitude:"\(coordinate.latitude)" , longitude: "\(coordinate.longitude)") { r in
                        switch r {
                        case .success(let addresses):
                            print("查询到的地址\(addresses)")
                            DispatchQueue.main.async {
                                if addresses.first != nil {
                                    let address =  addresses.first!
                                    print("longname 拿到了新的位置 \(address.longname ?? "无")")
                                    self.carOrder.startLabel = "\(address.longname ?? "无")"
                                }
    
                            }
                        case .failure(let addresses):
                            print("\(addresses)")
                        }
                    }
                }
    
                HStack(){
                    Image("首页_搜索").resizable().frame(width: 16,height: 16)
                    Text(carOrder.endLabel.isEmpty ? "您要去哪里?".localized() : carOrder.endLabel ).font(.system(size: 20,weight: .bold)).frame(maxWidth:.infinity,alignment: .leading)
                   
                }.background(.clear)
                .padding(.horizontal,15)
                .padding(.vertical,15)
                .overlay(
                    RoundedRectangle(cornerRadius: 16)
                        .stroke(.black, lineWidth: 2)
                ).onTapGesture(perform: {
                    self.showSelectMapEnd = true
                    if let pos = carOrder.endPos  {
                        region = MKCoordinateRegion(
                            center: CLLocationCoordinate2D(latitude: pos.latitude, longitude: pos.longitude),
                            span: MKCoordinateSpan(latitudeDelta: 0.005, longitudeDelta: 0.005)
                        )
    
                    } else {
                        region = MKCoordinateRegion(
                            center: CLLocationCoordinate2D(latitude: ViewModel.shared.lastLocation.latitude, longitude: ViewModel.shared.lastLocation.longitude),
                            span: MKCoordinateSpan(latitudeDelta: 0.005, longitudeDelta: 0.005)
                        )
                    }
                    print("tap end")
                }).fullScreenCover(isPresented: self.$showSelectMapEnd) {
                    // MARK: 下车位置--定位
                    ZStack {
                        //开始定位得到时候
                        if let pos = carOrder.startPos {
                            AddressManager(region: self.region, selectCoordinate: pos, selectType: "end"){
                                print("carOrder.startPos: \(carOrder.startPos) carOrder.startLabel:\(carOrder.startLabel)")
                                print("carOrder.endPos: \(carOrder.endPos) carOrder.endLabel:\(carOrder.endLabel)")
                                guard let coordinate = carOrder.startPos else{
                                    return
                                }
                                // 由于fullScreenCover(isPresented: self.$showSelectMapEn 这种模式弹出 不会调用 nearbyplace这个方法。所以选择完地址 必须要查一次
                               Api.googleNearbyPlaces(openId: vm.passenger.openId, latitude:"\(coordinate.latitude)" , longitude: "\(coordinate.longitude)") { r in
                                   switch r {
                                   case .success(let addresses):
                                       print("查询到的地址\(addresses)")
                                       DispatchQueue.main.async {
                                           if addresses.first != nil {
                                               let address =  addresses.first!
                                               print("longname 拿到了新的位置 \(address.longname ?? "无")")
                                               self.carOrder.startLabel = "\(address.longname ?? "无")"
                                           }
               
                                       }
                                   case .failure(let addresses):
                                       print("\(addresses)")
                                   }
                               }
                            }
                        } else {
                            AddressManager(region: self.region, selectCoordinate: vm.lastLocation, selectType: "end"){
                                let coordinate = carOrder.endPos!;
                                guard carOrder.endLabel.isEmpty else{
                                    return
                                }
//                               Api.googleNearbyPlaces(openId: vm.passenger.openId, latitude:"\(coordinate.latitude)" , longitude: "\(coordinate.longitude)") { r in
//                                   switch r {
//                                   case .success(let addresses):
//                                       print("查询到的地址\(addresses)")
//                                       DispatchQueue.main.async {
//                                           if addresses.first != nil {
//                                               let address =  addresses.first!
//                                               print("longname 拿到了新的位置 \(address.longname ?? "无")")
//                                               self.carOrder.endLabel = "\(address.longname ?? "无")"
//                                           }
//               
//                                       }
//                                   case .failure(let addresses):
//                                       print("\(addresses)")
//                                   }
//                               }
                            }
                        }
                    }
                }
                VStack{
                    HStack {
                              HStack{
                                  Image("首页_设置常用地址")
                                      .resizable()
                                      .frame(width: 16, height: 16)
              
                                  Text("设置常用地址").font(.system(size: 14)).foregroundColor(.black)
                              }
                              .frame(height:20)
                              .padding(.horizontal,10)
                              .padding(.vertical,10)
                              .background(Color(hex: "F1F3F4"))
                              .clipShape(RoundedRectangle(cornerRadius: 8))
                                          
                              }.background(
                                  NavigationLink(
                                    destination: CommonAddressView(){
                                        return
                                            logger.info("call texi ......")
                                            if passengerInfo.laosMobile.count == 0 && passengerInfo.wechatNo.count == 0 {
                                                needInputPassengerInfo = true
                                                return
                                            }
                                           
                                            let loc = CarOrder.shared.passengerPosition!
                            
                            
                                            var lat = UserDefaults.standard.double(forKey: "lastLocation.lat")
                                            var lon = UserDefaults.standard.double(forKey: "lastLocation.lon")
                            
                                            let passenger = PassengerInput().read()!
                            
                            
                                            if let pos = CarOrder.shared.startPos {
                                                lat = pos.latitude.rounded(6)
                                                lon = pos.longitude.rounded(6)
                                            }
                            
                                            var lat2 = 0.0
                                            var lon2 = 0.0
                            
                                            if let pos = CarOrder.shared.endPos {
                                                lat2 = pos.latitude.rounded(6)
                                                lon2 = pos.longitude.rounded(6)
                                            }
                            
                                            let calldata = DataCall(lon: lon, lat: lat,lon2: lon2, lat2: lat2, phone: passenger.laosMobile, wechat: passenger.wechatNo, peopleNum: viewStore.passengerNum)
                            
                                            logger.info("call data:\(calldata)")
                            
                                            Api.callCars(callInfo: calldata) { r in
                                                switch r {
                                                case .failure(let error):
                                                    logger.info("call cars error:\(error)")
                            
                                                case .success(let data):
                                                    logger.info("call cars: \(data)")
                            
                                                    DispatchQueue.main.sync {
                                                        vm.nearCarCount = data.driverCounts
                                                        logger.info("叫车返回车辆数量：\(data.driverCounts)")
                                                    }
                            
                                                    if let _ = data.workerID, let _ = data.name {
                                                        let carOrder = vm.order
                                                        carOrder.orderId = "\(data.id!)"
                                                        carOrder.driverId = data.openid!
                                                        carOrder.passengerId = calldata.openid
                                                        carOrder.driverPhone = "\(data.laosPhone!)"
                                                        carOrder.driverWechat = "\(data.phone ?? "")"
                                                        carOrder.carNo = data.chepai!
                                                        carOrder.save()
                                                        var linghuo = calldata
                                                        linghuo.hujiao = 1
                                                        linghuo.id = "\(data.id!)"
                                                        linghuo.receiverJSON = ""
                                                        var callInfos: [DataCall] = []
                                                        callInfos.append(linghuo)
                                                        service.callCar(callInfo: callInfos, orderId: carOrder.orderId, driverId: carOrder.driverId){
                                                            service.orderState = .calling
                                                        }
                                                    }
                                                }
                                            }
                                            //   }
                            
                                        
                                    },
                                      isActive: $isCommonActive,
                                      label: {
                                          EmptyView()
                                      }
                                  )
                              )
                              .onTapGesture {
                                  withAnimation {
                                      self.isCommonActive = true
                                      
                                  }
                              }
                    
                    
                }.padding(.top,10)
    
                Button {
                
                    
                    if LocationManager.shared.statusString == "unknown" || LocationManager.shared.statusString == "notDeterminded" || LocationManager.shared.statusString ==
                        "denied"
                    {
                        if let url = URL(string: "app-settings://LOCATION_SERVICES/com.jiaozichuxing.taxiapp") {
                            UIApplication.shared.open(url)
                        }
                        return
                    }
                    
                    
                    
                    
                    logger.info("call texi ......")
                    if passengerInfo.laosMobile.count == 0 && passengerInfo.wechatNo.count == 0 {
                        needInputPassengerInfo = true
                        return
                    }
                    
                    
                    self.needDistanceInfo = true;
                    //这里写
                    return
                    
                    
                    //   }
    
                } label: {
                    Label("呼叫出租车", systemImage: "car.fill")
                        .font(.system(size: 16))
                        .foregroundColor(Color(uiColor: .white))
                        .frame(width: geometry.size.width-30, height: 48)
                }
                .background(RoundedRectangle(cornerRadius: 6.0)
                    .fill(Color.themeColor())
                )
    
            }
            .padding(.horizontal,15)
            .padding(.top,15)
            .padding(.bottom,geometry.safeAreaInsets.bottom)
            .background(.linearGradient(Gradient(colors: [Color(hex: "#F8FFF8"),Color(hex: "#FCFBE4")]), startPoint: .leading, endPoint: .trailing))
            .clipShape(RoundedTopRectangle(cornerRadius: 20))
    
        }
    }
}

private extension ContentView {
    func createTopStatusView() -> some View {
        HStack {
            HStack {
                Image("home_setting")
                    .resizable()
                    .frame(width: 60, height: 60)
            }.background(
                NavigationLink(
                    destination: SettingView(passengerInfo: self.$passengerInfo),
                    isActive: $isSettingActive,
                    label: {
                        EmptyView()
                    }
                )
            )
            .background(Color.white)
            .cornerRadius(12)
            .padding(.horizontal,15)
            .padding(.top,15)
            
            .onTapGesture {
                withAnimation {
                    self.isSettingActive = true
                    
                }
            }
            Spacer()
//            HStack {
//                if vm.language == .Chinese {
//                    Text("中文").foregroundColor(.black)
//                        .font(.system(size: 16, weight: .medium))
//                } else if vm.language == .English {
//                    Text("English").foregroundColor(.black)
//                        .font(.system(size: 16, weight: .medium))
//                } else if vm.language == .Laos {
//                    Text("ພາສາລາວ").foregroundColor(.black)
//                        .font(.system(size: 16, weight: .medium))
//                }
//                Image("open")
//                    .resizable()
//                    .frame(width: 18, height: 18)
//            }.onTapGesture {
//                self.needLanguage.toggle()
//            }
//            .padding(20)
        }
    }
}
    
// struct ContentView_Previews: PreviewProvider {
//    static var previews: some View {
//        ContentView()
//    }
// }

struct ModuleView: View {
    var image : String
    var title : String
    var action : ()->Void
    
    var rImage: String
    var subAction : ()->Void
    
    var type : ModuleType
    
    @Binding var showingCustomAlert : Bool
    
    @State private var isOpen : Bool = false
    
    
    var body: some View {
        HStack {
            Button {
                self.showingCustomAlert = true;
            } label: {
                HStack{
                    Image(image)
                        .resizable()
                        .frame(width: 32, height: 32)
                        .foregroundColor(self.type == ModuleType.charging ? Color.themeColor() : Color.themeGreenColor())
                        .onTapGesture {
                            isOpen = !isOpen
                        }
                    if isOpen {
                        Text(title)
                            .foregroundColor(self.type == ModuleType.charging ? Color.themeColor() : Color.themeGreenColor())
                            .font(.system(size: 14))
                        Text("查看")
                            .padding(5)
                            .font(.system(size: 12))
                            .foregroundColor(self.type == ModuleType.charging ? Color.themeColor() : Color.themeGreenColor())
                            .overlay(
                                RoundedRectangle(cornerRadius: 10)
                                    .stroke((self.type == ModuleType.charging ? Color.themeColor() : Color.themeGreenColor()), lineWidth: 1)
                            )
                            .onTapGesture {
                                self.action()
                            }
                    }
                }
                .padding(.horizontal,4)
                .padding(.vertical,4)
                .background(Color(hex: self.type == ModuleType.charging ? "#FCF7F2" : "F5FFF5"))
                .clipShape(RoundedRectangle(cornerRadius: 5))
            }
            Spacer()
            Button {
                self.subAction()
            } label: {
                Image(rImage)
                    .resizable()
                    .frame(width: 40, height: 40)
            }
        }
        
    }
}

//弹出框
struct CustomAlertView: View {
    var title : String
    var content :String
    @Binding var showingCustomAlert : Bool
    var onConfirm: () -> Void = {}  // 确认按钮回调
    
    var body: some View {
        // 半透明背景
        Color.black.opacity(0.4)
            .edgesIgnoringSafeArea(.all)
            .onTapGesture {
                showingCustomAlert = false
            }
        
        // 自定义 Alert 内容
        VStack(spacing: 20) {
            Text(title)
                .font(.system(size: 24, weight: .bold)) // 自定义标题字体
                .padding(.top, 16)
            
            Text(content)
                .font(.system(size: 18)) // 自定义内容字体
                .multilineTextAlignment(.leading)
                .padding(.horizontal, 16)
                .lineSpacing(5)
            
            HStack {
                Button("关闭") {
                    showingCustomAlert = false
                    self.onConfirm()
                }
                .frame(maxWidth: .infinity)
                .padding()
                .font(.system(size: 22, weight: .bold))
                .foregroundColor(.black)
                
            }
            .padding(.horizontal, 16)
            .padding(.bottom, 16)
        }
        .background(Color.white)
        .cornerRadius(16)
        .padding(.horizontal, 40)
        .shadow(radius: 10)
    }
}
